from sqlalchemy.orm import Session
from typing import Optional, List
from app.models.iaro_career.program_date import ProgramDate
from app.schema.program_date_schema import ProgramDateCreate, ProgramDateUpdate

def get_program_date_by_code(db: Session, program_code: str) -> Optional[ProgramDate]:
    return db.query(ProgramDate).filter(ProgramDate.program_code == program_code).first()

def get_program_dates(db: Session, skip: int = 0, limit: int = 100) -> List[ProgramDate]:
    return db.query(ProgramDate).offset(skip).limit(limit).all()

def create_or_update_program_date(db: Session, data: ProgramDateCreate) -> ProgramDate:
    program = get_program_date_by_code(db, data.program_code)
    if program:
        for key, value in data.dict(exclude_unset=True).items():
            setattr(program, key, value)
    else:
        program = ProgramDate(**data.dict())
        db.add(program)
    db.commit()
    db.refresh(program)
    return program
